﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

/// <summary>
/// 飞行道具
/// </summary>
public class FlyObject : MonoBehaviour
{
    public CreatureInScene Owner;

    // 默认飞行方向
    public Vector3 DefautDirection;
    // 飞行速度
    public float Speed = 4;

    public float MaxFlyDistance = 20;

    private Rigidbody2D _rigidbody;
    private float _curFlyDistance = 0;

    // 击中回调
    public Action<CreatureInScene> HitCallback;

    void Start()
    {
        _rigidbody = gameObject.AddComponent<Rigidbody2D>();
        _rigidbody.gravityScale = 0;
        _rigidbody.useAutoMass = false;
        _rigidbody.isKinematic = true;

        // 有目标，追；没目标，向前
        var dir = DefautDirection;
        _rigidbody.velocity = DefautDirection * Speed;
    }

    void Update()
    {
        _curFlyDistance += Speed * Time.deltaTime;
        if (_curFlyDistance > MaxFlyDistance)
        {
            ReleaseSelf();
        }
        return;
        // 肯定有目标
        //_rigidbody.velocity = transform.forward * Speed;
    }

    void OnTriggerEnter2D(Collider2D collider)
    {
        if (Owner == null) { return; }
        if (collider.transform == Owner.Root) { return; }

        var creature = collider.GetComponent<Creature>();
        if (creature == null) { return; }

        // 是否可被攻击者攻击
        if (!creature.Owner.CanBeAttackBy(Owner)) { return; }

        hitTarget(creature.Owner);

        ReleaseSelf();
    }

    private void hitTarget(CreatureInScene target)
    {
        var zombie = target as ZombieInScene;
        if (zombie == null) { return; }

        target.BeHit(10, 1); // 若考虑火盆，可由飞行道具带回具体伤害值
    }

    private void ReleaseSelf()
    {
        ResMgr.instance.ReleaseObject(this.gameObject);
    }
}